//
//  AppDelegate.m
//  XPhoto
//
//  Created by baboy on 2019/2/20.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "AppDelegate.h"
#import "OpenUDID.h"
#import "DBCache.h"
#import <BKKit/BKApi.h>
#import "Theme.h"
#import "BKURLProtocol.h"
#import "QiniuConf.h"
#import "BKOperation.h"
#import "BKOperationQueue.h"
#import "User.h"
#import "HttpResponse.h"
#import "LoginViewController.h"
#import "BKNavigationController.h"
#import "ShareUtil.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import <UMCommonLog/UMCommonLogHeaders.h>
#import "Mem.h"
#import "SysDict.h"
#import <BKKit/UIWindow+x.h>
#import "BKWebViewController.h"
//genstrings -o en.lproj *.m
@interface AppDelegate ()
@property(nonatomic, strong) NSOperationQueue *queue;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // Override point for customization after application launch.
//    [NSURLProtocol registerClass:[BKURLProtocol class]];
//    Class cls = NSClassFromString(@"WKBrowsingContextController");
//    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
//    if ([cls respondsToSelector:sel]) {
//        // 通过http和https的请求，同理可通过其他的Scheme 但是要满足ULR Loading System
//        [cls performSelector:sel withObject:@"http"];
//        [cls performSelector:sel withObject:@"https"];
//    }
    
//    [Api checkVersionSuccess:^(id  _Nonnull task, id  _Nullable json) {
//        NSLog(@"error:%@",json);
//    }
//                     failure:^(id  _Nullable task, id  _Nullable json, NSError * _Nonnull error) {
//                         NSLog(@"error:%@",error);
//                     }];
    
    DLOG(@"device:%@", DEVICE_PARAM);
    //初始化骑牛配置
    [QiniuConf queryConfWithCallback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {

    }];
    [SysDict loadSysDict];
    //配置分享平台
    [ShareUtil configSharePlatforms];
    //配置分享参数
    [ShareUtil configShareSetting];

    [UMCommonLogManager setUpUMCommonLogManager];
    [UMConfigure setLogEnabled:YES];//设置打开日志
//    [UMConfigure initWithAppkey:[Mem valueForKey:@"umeng_app_key"] channel:@"App Store"];
    
    //接受更新用户信息的通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUser:) name:NOTIFICATION_USER_PROFILE_REFRESH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogin:) name:NOTIFICATION_USER_LOGIN object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(configFinished:) name:NOTIFICATION_CONFIG_FINISHED object:nil];
    [self updateApiCommonParams];
    return YES;
}
- (void)testBKQueue{
    self.queue = [[BKOperationQueue alloc] init];
    self.queue.maxConcurrentOperationCount = 2;
    for (NSInteger i = 0; i<10; i++) {
        BKOperation *op = [[BKOperation alloc] init];
        op.asynchronous = YES;
        WEAK(weakOp, op);
        [op addExecutionBlock:^{
            DLOG(@"==========start opetation:%ld, %@",i,[NSDate date]);
            dispatch_async(dispatch_get_main_queue(), ^{
                sleep(3.0f);
                DLOG(@"+++++++++++++finished:%ld, %@",i,[NSDate date])
                [weakOp updateFinishedStatus:YES];
                
            });
            sleep(2.0f);
        }];
        [self.queue addOperation:op];
    }
}
- (void)updateApiCommonParams{
    NSMutableDictionary *commonParams = [NSMutableDictionary dictionaryWithDictionary:DEVICE_PARAM];
    NSDictionary *authToken = [User authToken];
    if (authToken) {
        id tokenParam = @{@"ukey":authToken[@"ukey"]};
        [commonParams addEntriesFromDictionary:tokenParam];
    }
    [BKApi setCommonParams:commonParams];
}
- (void)userLogin:(NSNotification *)noti{
    [self updateApiCommonParams];
    [self userLoginAndConfigFinished];
}
/**
 *
 */
- (void)configFinished:(NSNotification *)noti{
    [self userLoginAndConfigFinished];
}
- (void)userLoginAndConfigFinished{
    SysDict *sysDict = [SysDict dictForKey:SYS_DICT_INTERCEP_HOST_KEY];
    if (sysDict && sysDict.items) {
        NSMutableArray *hosts = [NSMutableArray array];
        for (SysDictItem *item in sysDict.items) {
            [hosts addObject:item.value];
        }
        NSDictionary *authToken = [User authToken];
        NSDictionary *commonParams = [BKApi commonParams];
        NSMutableDictionary *headers = [NSMutableDictionary dictionary];
        if (authToken[@"domain"]) {
            headers[@"X-Host"] = authToken[@"domain"];
        }
        for (NSString *k in commonParams.allKeys) {
            NSString *headerKey = [NSString stringWithFormat:@"X-%@", [k capitalizedString]];
            headers[headerKey] = commonParams[k];
        }
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithCapacity:2];
        [userInfo setValue:headers forKey:BK_WEB_INJECTED_DATA_USERINFO_HEADER_KEY];
        if ([User currentUser]) {
            [userInfo setValue:[User currentUser] forKey:BK_WEB_INJECTED_DATA_USERINFO_USER_KEY];
        }
        [BKWebViewController injectUserInfo:userInfo cookies:authToken forHosts:hosts];
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

/**
 * 分享回调
 */
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}
@end
